<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" :close-on-click-modal="false">
    <el-form
      ref="addProductFormRef"
      :model="addProductFormData"
      :rules="addProductFormRules"
      label-width="80px"
      v-loading="formLoading"
    >
      <el-form-item label="商品名称" prop="name">
        <el-input v-model="addProductFormData.name" placeholder="请选择商品" />
        <el-button @click="openProductTableHandle">选择商品</el-button>
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-input-number v-model="addProductFormData.sort" controls-position="right" :min="0" />
      </el-form-item>      
    </el-form>
    <template #footer>
      <el-button @click="submitFormHandle" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
  <Dialog title="选择商品" v-model="choosProductTable" :close-on-click-modal="false" width="60%">
    <div style="width: 100%; height: 100%;">
      <el-row>
        <el-col :span="24">
          <el-form
            :model="queryProductParams"
            :inline="true"
            label-width="80px"
          >
          <el-form-item label="商品ID" prop="id">
              <el-input style="width: 120px;" v-model="queryProductParams.id" placeholder="请输入商品ID" />
            </el-form-item>
            <el-form-item label="商品名称" prop="name">
              <el-input style="width: 260px;" v-model="queryProductParams.name" placeholder="请输入商品名称" />
            </el-form-item>
            <el-form-item>
              <el-button @click="searchProduct" type="primary">搜 索</el-button>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-table v-loading="productListLoading" :data="productList">
            <el-table-column label="商品ID" min-width="90" prop="id" />
            <el-table-column label="封面图" min-width="120">
              <template #default="{ row }">
                <div class="flex" v-if="row.picUrl && row.picUrl != ''">
                  <el-image
                    fit="cover"
                    :src="row.picUrl"
                    class="flex-none w-50px h-50px"
                  />
                </div>
              </template>
            </el-table-column>
            <el-table-column align="center" label="商品名称" min-width="260" prop="name" />
            <!-- <el-table-column align="center" label="分类" min-width="100" prop="categoryName" />            -->
            <el-table-column align="center" label="价格" min-width="90" prop="price">
              <template #default="{ row }"> ¥ {{ fenToYuan(row.price) }}</template>
            </el-table-column>
            <el-table-column align="center" fixed="right" label="操作" min-width="200">
              <template #default="{ row }">
                <el-button            
                  link
                  type="primary"
                  @click="selectHandle(row)"
                >
                  选择
                </el-button>        
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
             <!-- 分页 -->
            <Pagination
                v-model:limit="queryProductParams.pageSize"
                v-model:page="queryProductParams.pageNo"
                :total="totalProduct"
                @pagination="searchProduct"
              />
        </el-col>
      </el-row>
    </div>
  </Dialog>
</template>
<script lang="ts" setup>
import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
import { CommonStatusEnum } from '@/utils/constants'
import { fenToYuan } from '@/utils'
import * as ProductSpuApi from '@/api/mall/product/spu'
import * as MallColumnApi from '@/api/mall/plate/column'

defineOptions({ name: 'ColumnAddProductForm' })

const props = defineProps({columnId: {type: Number}})

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const productListLoading = ref(false)
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const choosProductTable = ref(false)

const queryProductParams = ref({
  pageNo: 1,
  pageSize: 10,
  name: '',
  id: undefined,
  columnId: undefined
}) // 查询参数

const addProductFormData = ref({
  id: undefined,
  name: '',
  productId: undefined,
  columnId: undefined,
  sort: 0
})
const addProductFormRules = reactive({
  name: [{ required: true, message: '请选择商品', trigger: 'blur' }],
  productId: [{ required: true, message: '请选择商品', trigger: 'blur' }],
  sort: [{ required: true, message: '排序不能为空', trigger: 'blur' }]
})
const addProductFormRef = ref() // 表单 Ref
const totalProduct = ref(0) // 列表的总页数
const productList = ref<any[]>([]) // 列表的数据

const open = async (type: string, row) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (row) {
    formLoading.value = true
    try {
      addProductFormData.value.columnId = row.columnId
      addProductFormData.value.id = row.id
    } finally {
      formLoading.value = false
    }
  }
}

defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 选择商品 */
const selectHandle = (row) => {
  choosProductTable.value = false
  addProductFormData.value.name = row.name
  addProductFormData.value.productId = row.id
}

//打开选择商品表格
const openProductTableHandle = () => {
  choosProductTable.value = true
  searchProduct()
}

// 搜索商品
const searchProduct = async () => {
  productListLoading.value = true
  queryProductParams.value.columnId = props.columnId
  try {
    let data = await ProductSpuApi.getSpuSelectForPlate(queryProductParams.value)
    productList.value = data.list
    totalProduct.value = data.total
  }
  finally {
    productListLoading.value = false
  }  
}



/** 提交表单 */
const emit = defineEmits(['cancelFormHandle']) // 定义 success 事件，用于操作成功后的回调
const submitFormHandle = async () => {
  // 校验表单
  if (!addProductFormRef) return
  const valid = await addProductFormRef.value.validate()
  if (!valid) return
  // 提交请求
  formLoading.value = true
  try {
    const data = addProductFormData.value as MallColumnApi.ColumnProduct
    if (formType.value === 'create') {
      await MallColumnApi.addColumnProduct(data)
      message.success(t('common.createSuccess'))
    } else {
      await MallColumnApi.updateBrand(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('cancelFormHandle')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  addProductFormData.value = {
    id: undefined,
    name: '',
    picUrl: '',
    status: CommonStatusEnum.ENABLE,
    description: ''
  }
  addProductFormRef.value?.resetFields()
}
</script>
<style lang="scss" scoped>
 :deep(.el-input) {
    width: 70%;
  }
</style>